package cn.itcast.tanhua.mytanhuaserver.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.itcast.tanhua.mytanhuadubbointerface.api.QuanziApi;
import cn.itcast.tanhua.mytanhuadubbointerface.api.VisitorsApi;
import cn.itcast.tanhua.mytanhuaserver.interceptor.AliYunFilter;
import cn.itcast.tanhua.mytanhuaserver.service.ManualCheckService;
import cn.itcast.tanhua.mytanhuaserver.service.BlacklistService;
import cn.itcast.tanhua.mytanhuaserver.service.QuanziService;
import cn.itcast.tanhua.mytanhuaserver.service.UserInfoService;
import cn.itcast.tanhua.mytanhuaserver.service.UserService;
import cn.itcast.tanhua.pojo.*;
import cn.itcast.tanhua.utils.RelativeDateFormat;
import cn.itcast.tanhua.utils.UserThreadLocal;
import cn.itcast.tanhua.vo.*;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.aliyunpicuploadspringbootstart.service.PicUploadService;
import com.itheima.aliyunpicuploadspringbootstart.vo.PicUploadResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.sql.Date;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 郭文亮
 * @since 2021/11/28 21:00
 */
@Service
public class QuanziServiceImpl implements QuanziService {

    @Reference
    private QuanziApi quanziApi;

    @Autowired
    private UserService userService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private PicUploadService picUploadService;

    @Reference
    private VisitorsApi visitorsApi;

    @Autowired
    private BlacklistService blacklistService;

    @Autowired
    private QuanziMQService quanziMQService;

    @Autowired
    private AliYunFilter aliYunFilter;

    @Autowired
    private ManualCheckService manualCheckService;

    /**
     * 查看朋友圈信息
     * @param page 页码
     * @param pageSize 每页条数
     * @return 朋友圈的信息和朋友的信息
     */
    @Override
    public PageResult queryPublishList(Integer page, Integer pageSize) {
        // 封装结果集PageResult
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        // 1.通过token，获取user信息
        User userByToken = UserThreadLocal.get();

        //查询所有黑名单id，并过滤
        List<Long> blacklistById = blacklistService.queryBlacklistById(userByToken.getId());

        // 2.查询当前用户的好友动态列表
        PageInfo<Publish> publishPageInfo = this.quanziApi.queryPublishList(blacklistById,userByToken.getId(), page, pageSize);


        // 数据集存在records
        List<Publish> records = publishPageInfo.getRecords();
        if (CollUtil.isEmpty(records)) {
            return pageResult;
        }
        List<QuanZiVo> quanZiVoList = new ArrayList<>();
        // 3.遍历数据集records，将好友动态的信息封装到quanZiVoList
        for (Publish record : records) {
            QuanZiVo quanZiVo = new QuanZiVo();
            quanZiVo.setId(record.getId().toHexString());
            quanZiVo.setUserId(record.getUserId());
            quanZiVo.setTextContent(record.getText());
            quanZiVo.setImageContent(record.getMedias().toArray(new String[]{}));
            quanZiVo.setCreateDate(RelativeDateFormat.format(new Date(record.getCreated())));
            quanZiVoList.add(quanZiVo);
        }
        // 4.查询好友的用户信息，主要包括好友的头像、昵称
        List<Object> userIds = CollUtil.getFieldValues(records, "userId");
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoListByUserIds(userIds);
        // 5.遍历数据集userInfoList，将好友信息封装到quanZiVoList
        for (QuanZiVo quanZiVo : quanZiVoList) {
            for (UserInfo userInfo : userInfoList) {
                if (userInfo.getUserId().longValue() == quanZiVo.getUserId().longValue()) {
                    quanZiVo.setGender(userInfo.getSex().name().toLowerCase());
                    quanZiVo.setTags(StringUtils.split(userInfo.getTags(), ','));

                    quanZiVo.setCommentCount(0); //TODO 评论数
                    quanZiVo.setDistance("1.2公里"); //TODO 距离
                    quanZiVo.setHasLiked(0); //TODO 是否点赞（1是，0否）
                    quanZiVo.setLikeCount(0); //TODO 点赞数
                    quanZiVo.setHasLoved(0); //TODO 是否喜欢（1是，0否）
                    quanZiVo.setLoveCount(0); //TODO 喜欢数
                    break;
                }
            }
        }
        pageResult.setItems(quanZiVoList);
        return pageResult;
    }

    /**
     * 发送动态
     *
     * @param textContent   文本
     * @param location
     * @param latitude
     * @param longitude
     * @param multipartFile 图片
     * @return
     */
    @Override
    public String savePublish(String textContent, String location, String latitude, String longitude, MultipartFile[] multipartFile) {
        //查询当前的登录信息
        User user = UserThreadLocal.get();

        // 拦截动态文本到阿里云检测 - 胡桂明 2021/12/6 15:34
        String testing = null;
        try {
            testing = this.aliYunFilter.testing(textContent);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 判断文本
        if ("block".equals(testing)) {
            // 文本违规
            System.out.println("[自动审核]文本违规：" + testing);
            return null;
        }
        // 文本需要进一步人工审核
        if ("review".equals(testing)) {
            // TODO 文字人工审核
            System.out.println("[自动审核]文本无法识别，需要人工审核：" + testing);
            // this.人工审核(textContent) ---> 功炳
            return null;
        }

        // 提取图片文字检测 - 胡桂明 2021/12/8 10:52
        boolean imageFlag = this.aliYunFilter.extractImageText(multipartFile);
        if (!imageFlag) {
            System.out.println("[图片文字检测]图片内容有文本违规！");
            return null;
        }

        List<String> picUrls = new ArrayList<>();
        // 图片上传涉黄涉暴涉政检测
        for (MultipartFile file : multipartFile) {
            PicUploadResult picUploadResult = this.picUploadService.upload(file);
            picUrls.add(picUploadResult.getName());
        }
        // 拦截图片到阿里云检测 - 胡桂明 2021/12/6 19:52
        try {
            testing = this.aliYunFilter.imageReview(picUrls);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if ("block".equals(testing)) {
            // 图片违规
            System.out.println("[自动审核]图片违规：" + testing);
            return null;
        }
        // 图片需要进一步人工审核
        if ("review".equals(testing)) {
            // TODO 图片人工审核
//            System.out.println("需要人工审核");
            String publishId = manualCheckService.checkLetter(textContent, location, latitude, longitude, multipartFile);
            return publishId;
        }

        //封装publish
        Publish publish = new Publish();
        publish.setUserId(user.getId());
        publish.setText(textContent);
        publish.setLocationName(location);
        publish.setLatitude(latitude);
        publish.setLongitude(longitude);
        publish.setSeeType(1);
        //状态 1 -> 审核成功
        publish.setState(1);



        publish.setMedias(picUrls);
        String publishId = this.quanziApi.savePublish(publish);

        if(StrUtil.isNotEmpty(publishId)){
            //发送消息
            this.quanziMQService.publishMsg(publishId);
        }

        return publishId;
    }

    @Override
    public PageResult queryRecommendPublishList(Integer page, Integer pageSize) {
        //分析：通过dubbo中的服务查询系统推荐动态
        //通过mysql查询用户的信息，回写到结果对象中（QuanZiVo）

        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        //直接从ThreadLocal中获取对象
        User user = UserThreadLocal.get();

        //查询所有黑名单id，并过滤
        List<Long> blacklistById = blacklistService.queryBlacklistById(user.getId());


        //通过dubbo查询数据
        PageInfo<Publish> pageInfo = this.quanziApi.queryRecommendPublishList(blacklistById,user.getId(), page, pageSize);
        List<Publish> records = pageInfo.getRecords();
        if (CollUtil.isEmpty(records)) {
            return pageResult;
        }

        pageResult.setItems(this.fillQuanziVo(records));
        return pageResult;
    }

    /**
     * 根据查询到的publish集合填充QuanZiVo对象
     *
     * @param records
     * @return
     */
    private List<QuanZiVo> fillQuanziVo(List<Publish> records){
        List<QuanZiVo> quanZiVoList = new ArrayList<>();
        records.forEach(publish -> {
            QuanZiVo quanZiVo = new QuanZiVo();
            quanZiVo.setId(publish.getId().toHexString());
            quanZiVo.setTextContent(publish.getText());
            quanZiVo.setImageContent(publish.getMedias().toArray(new String[]{}));
            quanZiVo.setUserId(publish.getUserId());
            quanZiVo.setCreateDate(RelativeDateFormat.format(new Date(publish.getCreated())));

            quanZiVoList.add(quanZiVo);
        });

        //查询用户信息
        List<Object> userIds = CollUtil.getFieldValues(records, "userId");
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoListByUserIds(userIds);
        for (QuanZiVo quanZiVo : quanZiVoList) {
            //找到对应的用户信息
            for (UserInfo userInfo : userInfoList) {
                if(quanZiVo.getUserId().longValue() == userInfo.getUserId().longValue()){
                    this.fillUserInfoToQuanZiVo(userInfo, quanZiVo);
                    break;
                }
            }
        }

        return quanZiVoList;
    }

    /**
     * 填充用户信息
     *
     * @param userInfo
     * @param quanZiVo
     */
    private void fillUserInfoToQuanZiVo(UserInfo userInfo, QuanZiVo quanZiVo){
        BeanUtil.copyProperties(userInfo, quanZiVo, "id");
        quanZiVo.setGender(userInfo.getSex().name().toLowerCase());
        quanZiVo.setTags(StringUtils.split(userInfo.getTags(), ','));

        //当前用户
        User user = UserThreadLocal.get();

        quanZiVo.setCommentCount(0); //TODO 评论数
        quanZiVo.setDistance("1.2公里"); //TODO 距离
        quanZiVo.setHasLiked(this.quanziApi.queryUserIsLike(user.getId(), quanZiVo.getId()) ? 1 : 0); //是否点赞（1是，0否）
        quanZiVo.setLikeCount(Convert.toInt(this.quanziApi.queryLikeCount(quanZiVo.getId()))); //点赞数
        quanZiVo.setHasLoved(this.quanziApi.queryUserIsLove(user.getId(), quanZiVo.getId()) ? 1 : 0); //是否喜欢（1是，0否）
        quanZiVo.setLoveCount(Convert.toInt(this.quanziApi.queryLoveCount(quanZiVo.getId()))); //喜欢数
    }

    @Override
    public Long likeComment(String publishId) {
        User user = UserThreadLocal.get();
        //点赞
        Boolean result = this.quanziApi.likeComment(user.getId(), publishId);
        if(result){
            //发消息
            this.quanziMQService.likePublishMsg(publishId);

            //查询点赞数
            return this.quanziApi.queryLikeCount(publishId);
        }
        return null;
    }

    @Override
    public Long disLikeComment(String publishId) {
        User user = UserThreadLocal.get();
        //取消点赞
        Boolean result = this.quanziApi.disLikeComment(user.getId(), publishId);
        if(result){
            //发消息
            this.quanziMQService.disLikePublishMsg(publishId);
            //查询点赞数
            return this.quanziApi.queryLikeCount(publishId);
        }
        return null;
    }

    @Override
    public Long loveComment(String publishId) {
        User user = UserThreadLocal.get();
        //喜欢
        Boolean result = this.quanziApi.loveComment(user.getId(), publishId);
        if(result){
            //发消息
            this.quanziMQService.lovePublishMsg(publishId);
            //查询喜欢数
            return this.quanziApi.queryLoveCount(publishId);
        }
        return null;
    }

    /**
     * 取消喜欢
     * @param publishId
     * @return
     */
    @Override
    public Long disLoveComment(String publishId) {
        User user = UserThreadLocal.get();
        //取消喜欢
        Boolean result = this.quanziApi.disLoveComment(user.getId(), publishId);
        if(result){
            //发消息
            this.quanziMQService.disLovePublishMsg(publishId);
            //查询喜欢数
            return this.quanziApi.queryLoveCount(publishId);
        }
        return null;
    }

    @Override
    public QuanZiVo queryById(String publishId) {
        Publish publish = this.quanziApi.queryPublishById(publishId);
        if (publish == null) {
            return null;
        }
        //发消息
        this.quanziMQService.queryPublishMsg(publishId);
        return this.fillQuanziVo(Arrays.asList(publish)).get(0);
    }

    /**
     * 查询评论列表
     *
     * @param publishId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageResult queryCommentList(String publishId, Integer page, Integer pageSize) {

        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        User user = UserThreadLocal.get();

        //查询评论列表数据
        PageInfo<Comment> pageInfo = this.quanziApi.queryCommentList(publishId, page, pageSize);
        List<Comment> records = pageInfo.getRecords();
        if(CollUtil.isEmpty(records)){
            return pageResult;
        }

        //查询用户信息
        List<Object> userIdList = CollUtil.getFieldValues(records, "userId");
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoListByUserIds(userIdList);

        List<CommentVo> result = new ArrayList<>();
        for (Comment record : records) {
            CommentVo commentVo = new CommentVo();
            commentVo.setContent(record.getContent());
            commentVo.setId(record.getId().toHexString());
            commentVo.setCreateDate(DateUtil.format(new Date(record.getCreated()), "HH:mm"));
            //是否点赞
            commentVo.setHasLiked(this.quanziApi.queryUserIsLike(user.getId(), commentVo.getId()) ? 1 : 0);
            //点赞数
            commentVo.setLikeCount(Convert.toInt(this.quanziApi.queryLikeCount(commentVo.getId())));


            for (UserInfo userInfo : userInfoList) {
                if(ObjectUtil.equals(record.getUserId(), userInfo.getUserId())){

                    commentVo.setAvatar(userInfo.getLogo());
                    commentVo.setNickname(userInfo.getNickName());

                    break;
                }
            }

            result.add(commentVo);
        }

        pageResult.setItems(result);

        return pageResult;
    }

    /**
     * 发表评论
     * @param publishId
     * @param content
     * @return
     */
    @Override
    public Boolean saveComments(String publishId, String content) {
        User user = UserThreadLocal.get();
        Boolean result = this.quanziApi.saveComment(user.getId(), publishId, content);

        if(result){
            //发消息
            this.quanziMQService.commentPublishMsg(publishId);
        }

        return result;
    }

    @Override
    public PageResult queryAlbumList(Long userId, Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        //查询数据
        PageInfo<Publish> pageInfo = this.quanziApi.queryAlbumList(userId, page, pageSize);
        if(CollUtil.isEmpty(pageInfo.getRecords())){
            return pageResult;
        }

        //填充数据
        pageResult.setItems(this.fillQuanziVo(pageInfo.getRecords()));

        return pageResult;
    }

    @Override
    public List<VisitorsVo> queryVisitorsList() {
        User user = UserThreadLocal.get();
        List<Visitors> visitorsList = this.visitorsApi.queryMyVisitor(user.getId());
        if (CollUtil.isEmpty(visitorsList)) {
            return Collections.emptyList();
        }

        List<Object> userIds = CollUtil.getFieldValues(visitorsList, "visitorUserId");
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoListByUserIds(userIds);

        List<VisitorsVo> visitorsVoList = new ArrayList<>();

        for (Visitors visitor : visitorsList) {
            for (UserInfo userInfo : userInfoList) {
                if (ObjectUtil.equals(visitor.getVisitorUserId(), userInfo.getUserId())) {

                    VisitorsVo visitorsVo = new VisitorsVo();
                    visitorsVo.setAge(userInfo.getAge());
                    visitorsVo.setAvatar(userInfo.getLogo());
                    visitorsVo.setGender(userInfo.getSex().name().toLowerCase());
                    visitorsVo.setId(userInfo.getUserId());
                    visitorsVo.setNickname(userInfo.getNickName());
                    visitorsVo.setTags(StringUtils.split(userInfo.getTags(), ','));
                    visitorsVo.setFateValue(visitor.getScore().intValue());

                    visitorsVoList.add(visitorsVo);
                    break;
                }
            }
        }
        return visitorsVoList;
    }
}
